package com.canal.admin.handler;

import com.canal.admin.response.Result;
import com.canal.admin.response.ResultUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.canal.admin.service.UserTokenService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Administrator
 * @description
 * @date 2019年03月16 13:12
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    public UserTokenService userLoginService;

    public LoginSuccessHandler(UserTokenService userLoginService) {
        this.userLoginService = userLoginService;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        //生成token
        String token = userLoginService.saveUserLoginInfo((UserDetails) authentication.getPrincipal());
        //返回token
        response.setContentType("application/json;charset=utf8");
        Result<String> result = ResultUtil.makeSuccess("登录成功",token);
        ObjectMapper mapper = new ObjectMapper();
        String jsonResult = mapper.writeValueAsString(result);
        PrintWriter writer = response.getWriter();
        writer.write(jsonResult);
        writer.flush();
        writer.close();
    }
}
